package com.lz.ub.core

import com.lz.ub.*
import com.lz.ub.UBCOperator

/**
 * @author You
 * 主板重启器 主板重启, 此蓝牙板重启流程繁锁
 */
internal class UBCRestart(private val operator: UBCOperator) : UBCWritable {

    private var currentCommand: String? = null

    //指令超时
    private val runnable = Runnable {
        operator.log("restart timeout and write $COMMAND_START")
        currentCommand = COMMAND_START
        operator.write(currentCommand!!, this)
    }

    //发重启指令并超时+++
    fun restart() {
        currentCommand = COMMAND_RESTART
        operator.write(currentCommand!!, this)
        operator.postDelayed(runnable, COMMAND_START_TIMEOUT)
    }

    fun restartCallback() {
        Thread.sleep(COMMAND_CONNECTED_DELAYED)
        currentCommand = COMMAND_START
        operator.write(currentCommand!!, this)
    }

    override val label: String = "UBCRestart"

    override fun responseOk() {
        operator.log("restart ok callback and command = $currentCommand")
        when (currentCommand) {
            //RESTART响应的OK就继续等待,DEVICE START
            COMMAND_RESTART -> operator.removeCallbacks(runnable)
            COMMAND_START -> {
                Thread.sleep(COMMAND_CONNECTED_DELAYED)
                currentCommand = COMMAND_CANCEL_AUTO
                operator.write(currentCommand!!, this)
            }
            COMMAND_CANCEL_AUTO -> {
                Thread.sleep(COMMAND_CONNECTED_DELAYED)
                currentCommand = COMMAND_DISCONNECT
                operator.write(currentCommand!!, this)
            }
            COMMAND_DISCONNECT ->{
                currentCommand = null
                operator.restartOver()
            }
        }
    }

    override fun responseFail() {
        //nothing
    }

    override fun close() {
        operator.removeCallbacks(runnable)
        currentCommand = null
    }

    override fun isAvailable(): Boolean = currentCommand == null

    fun isExecuting(): Boolean = currentCommand != null
}